package main

import (
	"context"
	"fmt"
	"net/http"
	"os/signal"
	"syscall"
	"time"

	"gitee.com/h2ob/h2of/api"
	h2of "gitee.com/h2ob/h2of/base"
	"github.com/gin-gonic/gin"
)

func statTrace() gin.HandlerFunc {
	return func(c *gin.Context) {
		t := time.Now()
		c.Next()
		latency := time.Since(t)
		status := c.Writer.Status()
		h2of.GLogger.Infof("perf stat: url=[%s], time used=[%d], status=[%d]", c.FullPath(), latency.Milliseconds(), status)
	}
}

func jwtAuthMiddleware(c *gin.Context) {
}

func main() {
	conf := "../config/h2of.yaml"
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()
	h2of.GHBase.Init(conf)
	h2of.GLogger.Info("H2of Go")
	router := gin.New()
	router.MaxMultipartMemory = 8 << 20
	router.Use(statTrace())
	router.Use(gin.Recovery())
	api.RegisterApi(h2of.GConf.Http.Prefix, router, jwtAuthMiddleware)
	srv := &http.Server{
		Addr:    fmt.Sprintf(":%d", h2of.GConf.Http.Port),
		Handler: router,
	}

	// Initializing the server
	go func() {
		/**进行连接**/
		h2of.GLogger.Infof("server listen on:%d", h2of.GConf.Http.Port)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			h2of.GLogger.Errorf("listen error:%s", err.Error())
		}
	}()
	// wait
	<-ctx.Done()
	stop()
	h2of.GLogger.Info("Shutdown Server ...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		h2of.GLogger.Warn("Server shutdown:", err)
	}
	h2of.GLogger.Info("Server exist")
}
